package com.hanhai.zrb.api.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hanhai.common.cache.Cache;
import com.hanhai.zrb.api.biz.service.ResourceMatchCacheManager;
import com.hanhai.zrb.model.resourcematch.ResourceMatchContent;
import com.hanhai.zrb.model.resourcematch.ResourceMatchCondition;

@Service
public class ResourceMatchCacheManagerImpl implements ResourceMatchCacheManager {

	private static final int WEEK = 7 * 24 * 60 * 60;
	private static final int DAY = 1 * 24 * 60 * 60;
	private static final int HOUR = 1 * 60 * 60;
	private static final int MINUTE = 1 * 60;
	private static final int CATCHE_TIME = MINUTE;
	private Logger logger = Logger.getLogger(getClass());
	
	@Resource
	private Cache defaultCache;
	
	public void add(String key,List<ResourceMatchContent> list){
		String json = JSONObject.toJSONString(list);
		logger.info("save ResourceMatch ,json=" + json+",key="+key);
		defaultCache.add(key, json, CATCHE_TIME);
	}
	
	public List<ResourceMatchContent>  get(String key){
		List<ResourceMatchContent> listInRedis =null;
		Object jsonInRedis = defaultCache.getValue(key);
		if (jsonInRedis != null) {
			logger.info("get ResourceMatch,json=" + jsonInRedis+",key="+key);
			listInRedis = JSONObject.parseArray(jsonInRedis.toString(),
					ResourceMatchContent.class);
		}
		return listInRedis;
	}
	
	public void delete(String key){
		logger.info("delete ResourceMatch in redis,key="+key);
		defaultCache.delete(key);
	}

	/**
	 * 根据bizid和type，生成“bizid-key”格式的key
	 */
	public static String buildKey(ResourceMatchCondition matchResource) {
		return buildKey(matchResource.getBizid(),matchResource.getType());
	}
	
	public static String buildKey(Long bizid,Integer type){
		return "bizid"+bizid+"_"+"type"+type;
	}
}
